package han.parser;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @fileName: Regex
 * @author: Han
 * @date: 2018/6/4 10:26
 * @dscription: TODO
 */
public class Regex {

    public static final String NULL_MATCHING = "-";

    public static String deleteRedundantChar(String msg) {
        return msg.replaceAll("<[\\S\\s]*?[^<>]>", "")
                .replace("\n", "").replace(" ", "")
                .replace("\\/", "/").replace("&nbsp;", "");
    }

    /**
     * 使用正则表达式分割句子
     *
     * @param originStr 句子
     * @param regexStr  正则表达式
     * @return 分割后的句子
     */
    public static List<String> splitByRegex(String originStr, String regexStr) {

        List<String> list = new ArrayList<>();

        Pattern pattern = Pattern.compile(regexStr);
        Matcher matcher = pattern.matcher(originStr);
        int start = 0;
        int end = 0;
        while (matcher.find()) {
            end = matcher.start();
            String sentence = originStr.substring(start, end);
            start = matcher.end();
            if (!sentence.isEmpty()) {
                list.add(sentence);
            }
        }
        list.add(originStr.substring(end));
        return list;
    }

    /**
     * 使用指定正则表达式查找目的字符串
     *
     * @param originalStr 原始字符串
     * @param regex       正则表达式
     * @return 目的字符串
     */
    public static String matchString(String originalStr, String regex) {
        String desc;
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(originalStr);
        if (matcher.find()) {
            desc = matcher.group();
        } else {
            desc = NULL_MATCHING;
        }

        return desc;
    }
}